import re
import os
import logging
class FastaReader:
  def __init__(self):
    self.logger = logging.getLogger("FastaReader")
  def readFile(self, fileName):
    sequences = []
    print fileName
    f = open(fileName, 'r')
    buffer = "";
    for line in f:
      line = line.rstrip();
      line = line.lstrip();
      if re.match("[<>].*", line):      
        #REMOVE WHITE SPACE:
        buffer = re.sub("\\s*", "", buffer);
        buffer = re.sub("[0-9]*", "", buffer);
        if(buffer == ""):
          continue
        sequences.append(buffer.upper())
        buffer = ""
        continue
      buffer = buffer + line
    buffer = re.sub("\\s*", "", buffer)
    buffer = re.sub("[0-9]*", "", buffer)
    buffer = re.sub("\\\\", "", buffer)
    sequences.append(buffer.upper())
    f.close()
    
    return sequences
  def getTrainingData(self, trainingSet):
    import __main__
    if os.name == "nt":
      fullPath = os.getcwd()+"\\"+trainingSet
    else:
      fullPath = os.getcwd()+"/"+trainingSet
    if not os.path.exists(fullPath):
      raise Exception("the file or directory " + trainingSet + "does not exist\n")
    f = FastaReader
    sequences = dict()
    if not os.path.isdir(trainingSet):
      raise Exception("the file must be a directory\n")
    for dirpath, dirnames, files in os.walk(fullPath):
      import re
      if re.match('.*\..*', dirpath):
        continue
      for file in files:
        p = os.path.join(dirpath, file)
        sequences[file] = self.readFile(p)
    #self.logger.debug("getTrainingData"+str(sequences))
    return sequences

class AnnotationReader:
  def readFile(self, fileName):
    """
  CPGPLOT islands of unusual CG composition
hg18_dna from 1 to 817481

     Observed/Expected ratio > 0.60
     Percent C + Percent G > 50.00
     Length > 200

 Length 279 (133265..133543)

 Length 366 (136751..137116)
   """
    islands = []
    print fileName
    f = open(fileName, 'r')
    for line in f:
      if re.match('\s+Length\s+[0-9]*\s+\([0-9]*\.\.[0-9]*\).*', line):
        length, start, end = re.findall('[0-9]+', line)
        n = dict()
        n['length'] = int(length)
        n['start'] = int(start)
        n['end'] = int(end)
        islands.append(n)
        #print start + ".." + finish

    f.close()
    return islands
    
  def getAnnotationData(self, trainingSet):
    import __main__
    fullPath = os.path.join(os.getcwd(), trainingSet)
    if not os.path.exists(fullPath):
      raise Exception("the file or directory " + trainingSet + "does not exist\n")
    f = FastaReader
    annotations = dict()
    if not os.path.isdir(trainingSet):
      raise Exception("the file must be a directory\n")
    for dirpath, dirnames, files in os.walk(fullPath):
      import re
      if re.match('.*\..*', dirpath):
        continue
      for file in files:
        p = os.path.join(dirpath, file)
        annotations[file] = self.readFile(p)
    logging.debug("getAnnotationData: " + str(annotations))
    return annotations
      
